package com.bidianying.task;

import java.util.HashMap;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import redis.clients.jedis.ShardedJedisPool;

import com.bidianying.service.GewaraService;
import com.bidianying.service.WebService;
import com.bidianying.util.JsonUtil;
import com.bidianying.util.LoadProperties;
import com.bidianying.util.RedisUtils;


@Component 
public class GewaraTask {
	
	
	@Autowired
	private GewaraService gewaraService;
	@Autowired
	private WebService webService;
	@Autowired
	private ShardedJedisPool shardedJedisPool;
	
	
	@Scheduled(cron = "0 46 17 * * ?") 
    public void job1() { 
    	System.out.println("定时任务开始--》");
//    	int i = gewaraService.saveCityIdForGewara(); 
    	System.out.println("定时任务结束--》");
    }  
	//从格瓦拉定时拉取全部城市的影片信息,放入redis中
    @Scheduled(cron = "0 25 14 * * ?")  
    public void job2() { 
    	System.out.println("定时任务job2开始--》");
    	JSONArray cityArray = gewaraService.getCity();
    	for(Object o:cityArray){
    		JSONObject city = (JSONObject) o;
    		String citycode = city.getString("code");
    		String url = LoadProperties.getProperty("/config.properties", "gewaraFilm");
    		Map<String,String> data = new HashMap<String,String>();
    		Map<String,Object> map = webService.getFilmInfoByUrl(url, data,citycode);
    		if(map.containsKey("data")){
    			Map<String,String> resultMap = new HashMap<String,String>();
        		resultMap.put("filmNum", String.valueOf(map.get("filmNum")));
        		resultMap.put("data", JsonUtil.toJSON(map.get("data")));
        		RedisUtils.hmset(shardedJedisPool, "cityFilmInfo:"+citycode, resultMap, 30*60*60);
        		System.out.println(city.getString("name")+"===已存入redis==="+citycode);
    		}
    		try {
				Thread.sleep(500);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
    	}
    	System.out.println("定时任务job2结束--》");
    }  
    //从格瓦拉拉取电影并存入数据库
    @Scheduled(cron = "0 36 14 * * ?")  
    public void job3() { 
    	System.out.println("定时任务job3开始--》");
    	gewaraService.saveMovieInfo();
    	System.out.println("定时任务job3结束--》");
    } 
    
    //拉取格瓦拉的影院信息
    @Scheduled(cron = "0 20 20 * * ?")  
    public void job4() { 
    	System.out.println("gewara定时任务job4开始--》");
    	//gewaraService.saveGewaraCinemaInfo();
    	System.out.println("gewara定时任务job4结束--》");
    } 
    
    
    
}
